#coding:utf-8

import joblib
import pandas as pd
import copy
import numpy as np
from os import path
import os
from .forcast_info import col_var,col_var2,df_aggregation,do_aggregations

import lightgbm
import json

#调用lightgbm模型
class forcast_model:
    def get_forcast(place,date):
        model = joblib.load("Predict/models/lightgbm/fatal.pkl")
        model2 = joblib.load("Predict/models/lightgbm/case.pkl")
        model_pri = joblib.load("Predict/models/lightgbm/final_fatal.pkl")
        model2_pri = joblib.load("Predict/models/lightgbm/final_case.pkl")

        df_traintest10 = pd.read_csv('Predict/dataset/afterdatanew.csv')

        last_day_train = df_traintest10['day'][pd.isna(df_traintest10['ForecastId'])].max()


        df_interest_base = df_traintest10[df_traintest10['place_id'] == place].reset_index(drop=True)
        df_interest = copy.deepcopy(df_interest_base)
        df_interest['ConfirmedCases'] = df_interest['ConfirmedCases'].astype(np.float)
        df_interest['cases/day'] = df_interest['cases/day'].astype(np.float)
        df_interest['fatal/day'] = df_interest['fatal/day'].astype(np.float)
        df_interest['Fatalities'] = df_interest['Fatalities'].astype(np.float)
        df_interest['cases/day'][df_interest['day'] > last_day_train] = -1
        df_interest['fatal/day'][df_interest['day'] > last_day_train] = -1
        len_known = (df_interest['cases/day'] != -1).sum()
        len_unknown = (df_interest['cases/day'] == -1).sum()
        print("len train: {}, len prediction: {}".format(len_known, len_unknown))

        X_valid = df_interest[col_var][df_interest['day'] > 84]
        X_valid2 = df_interest[col_var2][df_interest['day'] > 84]
        pred_f = np.exp(model.predict(X_valid)) - 1
        pred_c = np.exp(model2.predict(X_valid2)) - 1
        df_interest['fatal/day'][df_interest['day'] > last_day_train] = pred_f.clip(0, 1e10)
        df_interest['cases/day'][df_interest['day'] > last_day_train] = pred_c.clip(0, 1e10)
        df_interest['Fatalities'] = np.cumsum(df_interest['fatal/day'].values)
        df_interest['ConfirmedCases'] = np.cumsum(df_interest['cases/day'].values)
        for j in range(len_unknown):  # use predicted cases and fatal for next days' prediction
            X_valid = df_interest[col_var].iloc[j + len_known]
            X_valid2 = df_interest[col_var2].iloc[j + len_known]
            pred_f = model_pri.predict(X_valid)
            pred_c = model2_pri.predict(X_valid2)
            pred_c = (np.exp(pred_c) - 1).clip(0, 1e10)
            pred_f = (np.exp(pred_f) - 1).clip(0, 1e10)
            df_interest['fatal/day'][j + len_known] = pred_f
            df_interest['cases/day'][j + len_known] = pred_c
            df_interest['Fatalities'][j + len_known] = df_interest['Fatalities'][j + len_known - 1] + pred_f
            df_interest['ConfirmedCases'][j + len_known] = df_interest['ConfirmedCases'][j + len_known - 1] + pred_c
            df_interest = df_interest.drop([
                'cases/day-(1-1)', 'cases/day-(1-7)', 'cases/day-(8-14)', 'cases/day-(15-21)',
                'fatal/day-(1-1)', 'fatal/day-(1-7)', 'fatal/day-(8-14)', 'fatal/day-(15-21)',
                'days_since_1cases', 'days_since_10cases', 'days_since_100cases',
                'days_since_1fatal', 'days_since_10fatal', 'days_since_100fatal', ], axis=1)
            df_interest = do_aggregations(df_interest.reset_index(drop=True))

        df = df_interest[df_interest["day"] > 91]
        #df2=df[['Country/Region','Date','ConfirmedCases','Fatalities']]
        df2 = df[[ 'Date', 'ConfirmedCases', 'Fatalities']]
        df2.columns=[ 'Date', 'predConfirmedCases', 'predFatalities']
        df3=df2.reset_index(drop=True)
        dfneed1 = df3.loc[df3['Date'] == date]
        dfneed = dfneed1[[ 'predConfirmedCases', 'predFatalities']]

        df_json = dfneed.to_json(orient='records',force_ascii=False)
        return json.loads(df_json)
